/**
 * @author 'yejinbo'
 * @description `Vue中间件测试`
 */
import axios from 'axios'
import Vue from 'vue'
const HTMLEvs = ['abort', 'blur', 'change', 'error', 'focus', 'load', 'reset', 'resize', 'scroll', 'select', 'submit', 'unload']
const UIEvs = ['DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'keydown', 'keypress', 'keyup']
const MouseEvs = ['click', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup']
const FORMELES = ['INPUT', 'SELECT', 'TEXTAREA', 'DATALIST', 'KEYGEN', 'OUTPUT']
const isDom = vm => {
  if (!vm) throw new Error('can not find element of undefined')
  if (!window.HTMLElement) {
    return vm && typeof vm === 'object' && vm.nodeType && vm.nodeType === 1 && vm.nodeName && typeof vm.nodeName === 'string'
  } else {
    return vm instanceof HTMLElement
  }
}
const find = vm => {
  if (!isDom(vm)) return false
  else {
    if (vm.nodeType === 1) {
      if (FORMELES.includes(vm.nodeName)) return vm
      else {
        if (!vm.children) return false
        else {
          let children = Array.prototype.slice.call(vm.children)
          let l = children.length
          if (l > 0) {
            if (l === 1) return find(children[0])
            for (let i = 0; i < l; i++) {
              let t = find(children[i])
              if (!isDom(t)) continue
              else return t
            }
          }
        }
      }
    } else return false
  }
}
export default {
  trigger (type, bubbles) {
    let _vm = null
    bubbles = bubbles || true
    let isCom = null
    if (!isDom(this)) {
      if (this instanceof Vue) isCom = isDom(this.$el)
      else throw new Error('unexpected argument')
    } else {
      _vm = this
    }
    if (isCom) _vm = find(this.$el)
    if (document.all || document.createEventObject) {
      _vm.fireEvent(`on${type}`)
      return
    }
    let e = null
    let _e = document.createEvent
    if (HTMLEvs.includes(type)) {
      e = _e('HTMLEvents')
      e.initEvent(type, bubbles, true)
    }
    if (UIEvs.includes(type)) {
      e = _e('UIEvents')
      e.initUIEvent(type, bubbles, true, window.document, 1)
    }
    if (MouseEvs.includes(type)) {
      e = _e('MouseEvents')
      e.initMouseEvent(type, bubbles, true, window.document, 1)
    }
    if (!e) throw new Error('denied the event type')
    _vm.dispatchEvent(e)
  },
  install (Vue) {
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
    Vue.prototype.$axios = axios
    Vue.prototype.$trigger = this.trigger
  }
}
